package workexp.alg.question.tree;

import org.junit.Test;
import workexp.alg.env.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class LevelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if(root==null){
            return result;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            //因为queue每次只处理了一层因此size为该层的节点数，便利了size个节点后当前层数值即为空
            int levelNum =queue.size();
            List<Integer> subList = new ArrayList<>();
            for (int i = 0; i <levelNum ; i++) {
                TreeNode cur = queue.poll();
                subList.add(cur.val);
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
            result.add(subList);


        }
        return result;
    }

    @Test
    public  void test(){
        Integer[] nums = {3,9,20,null,null,15,7};
        TreeNode root = TreeNode.createTree(nums);
        System.out.println(root);
        TreeNode.show(root);
        List<List<Integer>> result = levelOrder(root);
        System.out.println(result);
    }
}
